<template>
  <view class="container">
    <!-- 搜索栏 -->
    <view class="search-bar">
      <view class="search-input" @click="goToSearch">
        <u-icon name="search" size="20" color="#999"></u-icon>
        <text class="search-placeholder">搜索菏泽本地信息...</text>
      </view>
    </view>

    <!-- 分类筛选 -->
    <view class="filter-bar">
      <view class="filter-item" @click="showCategoryPicker = true">
        <text>{{ currentCategory?.name || '全部' }}</text>
        <u-icon name="arrow-down" size="16"></u-icon>
      </view>
      <view class="filter-item" @click="toggleSortBy">
        <text>{{ sortByText }}</text>
        <u-icon name="arrow-down" size="16"></u-icon>
      </view>
    </view>

    <!-- 信息列表 -->
    <scroll-view
      class="post-list"
      scroll-y
      :refresher-enabled="true"
      :refresher-triggered="refreshing"
      @refresherrefresh="onRefresh"
      @scrolltolower="onLoadMore"
    >
      <post-card
        v-for="post in postList"
        :key="post.id"
        :post="post"
        @click="goToDetail(post.id)"
      />

      <!-- 加载状态 -->
      <view v-if="loading" class="loading-status">
        <u-loading mode="circle"></u-loading>
        <text class="ml-sm">加载中...</text>
      </view>

      <!-- 没有更多 -->
      <view v-if="!hasMore && postList.length > 0" class="no-more">
        没有更多了
      </view>

      <!-- 空状态 -->
      <view v-if="!loading && postList.length === 0" class="empty-state">
        <u-empty mode="list" text="暂无信息"></u-empty>
      </view>
    </scroll-view>

    <!-- 分类选择器 -->
    <u-picker
      :show="showCategoryPicker"
      :columns="categoryColumns"
      @confirm="onCategoryConfirm"
      @cancel="showCategoryPicker = false"
    ></u-picker>
  </view>
</template>

<script setup lang="ts">
import { ref, computed, onMounted, onShow } from 'vue'
import { onPullDownRefresh, onReachBottom } from '@dcloudio/uni-app'
import { useAppStore } from '@/store/app'
import { useUserStore } from '@/store/user'
import { postApi } from '@/api'
import type { Post, Category } from '@/types'
import PostCard from './components/PostCard.vue'

// Store
const appStore = useAppStore()
const userStore = useUserStore()

// 状态
const postList = ref<Post[]>([])
const loading = ref(false)
const refreshing = ref(false)
const hasMore = ref(true)
const page = ref(1)
const pageSize = 10

// 筛选条件
const currentCategory = ref<Category | null>(null)
const sortBy = ref<'time' | 'distance' | 'hot'>('time')
const showCategoryPicker = ref(false)

// 计算属性
const sortByText = computed(() => {
  const map = {
    time: '最新',
    distance: '距离',
    hot: '热门'
  }
  return map[sortBy.value]
})

const categoryColumns = computed(() => {
  return [
    [
      { text: '全部', value: 0 },
      ...appStore.mainCategories.map(cat => ({
        text: cat.name,
        value: cat.id
      }))
    ]
  ]
})

// 生命周期
onMounted(async () => {
  // 初始化应用数据
  await appStore.init()

  // 获取用户位置
  if (!userStore.location) {
    await userStore.getLocation()
  }

  // 加载列表
  loadPostList()
})

onShow(() => {
  // 刷新列表(从详情页返回时)
  if (postList.value.length > 0) {
    onRefresh()
  }
})

// 下拉刷新
onPullDownRefresh(async () => {
  await onRefresh()
  uni.stopPullDownRefresh()
})

// 上拉加载
onReachBottom(() => {
  onLoadMore()
})

/**
 * 加载信息列表
 */
const loadPostList = async (isRefresh = false) => {
  if (loading.value) return

  loading.value = true

  try {
    const params: any = {
      page: isRefresh ? 1 : page.value,
      size: pageSize,
      sortBy: sortBy.value
    }

    // 添加分类筛选
    if (currentCategory.value) {
      params.categoryId = currentCategory.value.id
    }

    // 添加位置信息
    if (sortBy.value === 'distance' && userStore.location) {
      params.lat = userStore.location.lat
      params.lng = userStore.location.lng
    }

    const res = await postApi.getList(params)

    if (isRefresh) {
      postList.value = res.list
      page.value = 1
    } else {
      postList.value.push(...res.list)
    }

    hasMore.value = res.pagination.hasMore
    page.value++
  } catch (err) {
    console.error('加载列表失败:', err)
  } finally {
    loading.value = false
    refreshing.value = false
  }
}

/**
 * 下拉刷新
 */
const onRefresh = async () => {
  refreshing.value = true
  await loadPostList(true)
}

/**
 * 上拉加载更多
 */
const onLoadMore = () => {
  if (!hasMore.value || loading.value) return
  loadPostList()
}

/**
 * 切换排序方式
 */
const toggleSortBy = () => {
  const sortTypes: Array<'time' | 'distance' | 'hot'> = ['time', 'distance', 'hot']
  const currentIndex = sortTypes.indexOf(sortBy.value)
  sortBy.value = sortTypes[(currentIndex + 1) % sortTypes.length]

  // 重新加载
  onRefresh()
}

/**
 * 分类选择确认
 */
const onCategoryConfirm = (e: any) => {
  const selectedValue = e.value[0]
  showCategoryPicker.value = false

  if (selectedValue === 0) {
    currentCategory.value = null
  } else {
    currentCategory.value = appStore.getCategoryById(selectedValue) || null
  }

  // 重新加载
  onRefresh()
}

/**
 * 跳转到搜索页
 */
const goToSearch = () => {
  uni.navigateTo({
    url: '/pages/search/index'
  })
}

/**
 * 跳转到详情页
 */
const goToDetail = (postId: number) => {
  uni.navigateTo({
    url: `/pages/detail/index?id=${postId}`
  })
}
</script>

<style lang="scss" scoped>
.container {
  height: 100vh;
  display: flex;
  flex-direction: column;
  background-color: var(--bg-color-page);
}

.search-bar {
  padding: var(--spacing-md);
  background-color: var(--bg-color);

  .search-input {
    display: flex;
    align-items: center;
    padding: 16rpx 24rpx;
    background-color: var(--bg-color-page);
    border-radius: var(--radius-round);

    .search-placeholder {
      margin-left: var(--spacing-sm);
      color: var(--text-color-placeholder);
      font-size: 28rpx;
    }
  }
}

.filter-bar {
  display: flex;
  padding: var(--spacing-sm) var(--spacing-md);
  background-color: var(--bg-color);
  border-bottom: 1rpx solid var(--border-color-light);

  .filter-item {
    display: flex;
    align-items: center;
    padding: 8rpx 16rpx;
    margin-right: var(--spacing-md);
    font-size: 28rpx;
    color: var(--text-color);

    text {
      margin-right: 8rpx;
    }
  }
}

.post-list {
  flex: 1;
  padding: var(--spacing-md);
}

.loading-status {
  display: flex;
  align-items: center;
  justify-content: center;
  padding: var(--spacing-md);
  color: var(--text-color-secondary);
  font-size: 28rpx;
}

.no-more {
  text-align: center;
  padding: var(--spacing-md);
  color: var(--text-color-placeholder);
  font-size: 24rpx;
}

.empty-state {
  padding: 200rpx 0;
}
</style>
